/**
 * @author:linjiye
 * @date:2025/1/6
 * @desc:
 **/

import {StyleSheet, Text, TouchableOpacity, View} from 'react-native'
import React, {useEffect, useState} from 'react'
import TabCard from "@/components/TabCard";
import PageFormBtn from "@/components/PageFormBtn";
import {useLocalSearchParams, useRouter} from "expo-router";
import PageScrollView from "@/components/PageScrollView";
import PageTabBar from "@/components/PageTabBar";
import ContentFeed from "@/components/aiFeeding/ContentFeed";
import FileFeed from "@/components/aiFeeding/FileFeed";
import {useDispatch, useSelector} from "react-redux";
import {
    useAddLabelMutation,
    useBatchSetLabelMutation, useDeleteFileMutation, useDelLabelMutation,
    useGetRateFromCodeQuery, useLabelListQuery,
    useProfitModelMutation
} from "@/store/api/aiFeeding/aiFeedingApi";
import FcButton from "@/components/FcButton";
import KeywordHighlighter from "@/components/KeywordHighlighter";
import FcModal from "@/components/FcModal";
import FormTitle from "@/components/FormTitle";
import {Flex, Toast} from "@ant-design/react-native";
import FcTextInput from "@/components/FcTextInput";
import useGetStorage from "@/hooks/useGetStorage";
import {set_selectFileList} from "@/store/reducer/aiFeeding/aiFeedingSlice";

type Props = {}

const details = (props: Props) => {
    const [pageScrollBodyH, setPageScrollBodyH] = useState(0)
    const [tabList, setTabList] = useState([
        {
            name: '产品内容投喂',
            val: 1,
            icon: require('@/assets/images/aiOriginality/tab_select_left.png'),
            icon1: require('@/assets/images/aiOriginality/tab_noselect_left.png'),
            style: {
                marginRight: -15,
                position: "relative",
                zIndex: 100,
            }
        }, {
            name: '视频/图片投喂',
            val: 2,
            icon: require('@/assets/images/aiOriginality/tab_noselect_right.png'),
            icon1: require('@/assets/images/aiOriginality/tab_select_right.png'),
            style: {
                marginLeft: -15,
                position: "relative",
                zIndex: 100,
            }
        }
    ])
    const [selectVal, setSelectVal] = useState(1)
    const [disable, setDisabled] = useState(true)
    const [selectFileData,setSelectFileData] = useState([])
    const [setTap,SetSetTap] = useState(false)
    const [seleteLabel, setSelectLabel] = useState({})
    const [isAdd,setIsAdd] = useState(false)
    const [tapName,setTapName] = useState('')
    const [hint,setHint] = useState('')
    const [hintTitle,setHintTitle] = useState('')
    const [isHint,setIsHint] = useState(false)
    const [checkType,setCheckType] = useState(0)

    const [productId,setProductId] = useState('')
    const [contentParams,setContentParams] = useState({})
    const [labelList,setLabelList] = useState([])
    const [synchronize,setSynchronize] = useState(false)

    const [profitModelFun] = useProfitModelMutation()
    const [batchSetLabelFun] = useBatchSetLabelMutation()
    const [deleteLabelFun] = useDelLabelMutation()
    const [deleteFileFun] = useDeleteFileMutation()
    const {data:labelData,isSuccess:labelSuccess,refetch:labelRefetch} = useLabelListQuery({
        name: '',
        pageSize: 1000
    })
    const [addLabelFun] = useAddLabelMutation()



    const router = useRouter();
    const {id,name} = useLocalSearchParams()

    const dispatch = useDispatch();


    const selectItem = useSelector(state => state.aiFeeding.selectItem)
    const selectFileList = useSelector(state => state.aiFeeding.selectFileList)




    useEffect(() => {
        if(id) setProductId(id)
        if(selectItem){
            setContentParams(selectItem)
            let disable = !(selectItem?.productCustomer && selectItem?.productCustomer != '' && selectItem?.productInformation && selectItem?.productInformation != '')
            setDisabled(disable)
        }
        if(selectFileList){
            setSelectFileData(selectFileList)
        }
        if(labelData){
            let list = labelData?.result?.records || []
            let newList = [
                {
                    title: '全部标签',
                    id: null,
                },{
                    title: '无标签',
                    id: 0,
                }
            ]
            list?.map((item, index) => {
                newList.push({
                    ...item,
                    title: item.name
                })
            })
            setLabelList(newList)
        }
    }, [id,selectItem,selectFileList,labelData,labelSuccess]);


    function getScrollBodyInfo({height}) {
        setPageScrollBodyH(height)
    }

    const handleTabCardClick = (data) => {
        setSelectVal(data.val)
    }
    const handlePageFormBtnClick = (val) => {
        // router.navigate('/aiOriginality/result')
        // if(contentParams?.productCustomer === contentParams?.productCustomerOld && contentParams?.productInformation === contentParams?.productInformationOld) {
        //     return
        // }
        setSynchronize(false)

        profitModelFun({
            productCustomer:contentParams?.productCustomer,
            productInformation:contentParams?.productInformation,
            groupId:contentParams?.groupId || productId,
            status: 1,
            typeKey:contentParams?.value,
        }).then(res => {
            console.log(res);
            if(res.data?.code === 200) {
                Toast.info('同步成功')
                setSynchronize(true)
                // getProfitModelInfo(productId,profitList)
            }
        })
    }

    function handleDelete() {
        setHint('一旦删除，当前标签将被删除哦~')
        setHintTitle('确认要删除标签吗？')
        setIsHint(true)
        setCheckType(1)
    }

    function handleClearTap() {
        setHint('一旦清空，当前标签将被清空哦~')
        setHintTitle('确认要清空标签吗？')
        setIsHint(true)
        setCheckType(2)
    }

    function handleSetTap() {
        console.log(labelList);
        SetSetTap(true)
    }

    function handleToSetTap() {
        batchSetLabelFun({
            labelIds:seleteLabel.id,
            libraryIds:selectFileData.map(item => item.id).toString(),
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                SetSetTap(false)
                dispatch(set_selectFileList([]))
                Toast.info('设置成功')
            }
        })
    }

    function handleSure() {
        if(checkType === 1) handleToDeleteFile()
        else handleToDeleteTap()
    }

    function handleToDeleteFile() {
        deleteFileFun({
            id:selectFileData.map(item => item.id).toString(),
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                dispatch(set_selectFileList([]))
                setIsHint(false)
                Toast.info('删除成功')
            }
        })
    }

    function handleToDeleteTap() {
        deleteLabelFun({
            libraryIds:selectFileData.map(item => item.id).toString(),
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                dispatch(set_selectFileList([]))
                setIsHint(false)
                Toast.info('清空成功')
            }
        })
    }

    function handleAddLabel() {
        addLabelFun({
            name:tapName,
        }).then(res => {
            console.log(res);
            if(res.data.code === 200) {
                Toast.info('添加成功')
                setTapName('')
                setIsAdd(false)
                labelRefetch()
            }
        })
    }

    return (
        <PageScrollView
            bodyStyle={{paddingBottom: 0}}
            getPageScrollBodyInfo={getScrollBodyInfo}
            pageTab={
                <PageTabBar
                    style={{marginVertical: 10}}
                    content={
                        <Text style={{color: 'rgba(0, 0, 0, 0.9)', fontSize: 17,fontWeight: 600}}>
                            <Text style={{color: '#2856FF', fontSize: 17}}>{name}</Text>的产品资料
                        </Text>
                    }
                />
            }
            pageHeader={
                <TabCard tabList={tabList} selectVal={selectVal} onTabCardClick={(val) => handleTabCardClick(val)}/>
            }
            pageBottom={
                <View>
                    {selectVal === 1 &&
                        <PageFormBtn disable={disable} btnName='同步到产品资料库' onPageFormBtnClick={handlePageFormBtnClick}/>
                    }
                    {selectVal === 2 &&
                        <View style={styles.page_bottom}>
                            <Text style={styles.btn_item}>已选 {selectFileData?.length} 个</Text>
                            <TouchableOpacity style={styles.btn_item} onPress={() => handleSetTap()}>
                                <Text style={[styles.btn_icon,selectFileData?.length>0&&styles.btn_txt]}>&#xe631;</Text>
                                <Text
                                    style={[styles.btn_icon, selectFileData?.length>0 && styles.btn_txt]}>设置标签</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.btn_item} onPress={() => handleClearTap()}>
                                <Text style={[styles.btn_icon,selectFileData?.length>0&&styles.btn_txt]}>&#xe6c7;</Text>
                                <Text
                                    style={[styles.btn_icon, selectFileData?.length>0 && styles.btn_txt]}>清空标签</Text>
                            </TouchableOpacity>
                            <TouchableOpacity style={styles.btn_item} onPress={() => handleDelete()}>
                                <Text style={[styles.delete_text,selectFileData?.length===1&&styles.delete_active]}>&#xe61d;</Text>
                                <Text
                                    style={[styles.delete_text, selectFileData?.length===1 && styles.delete_active]}>删除素材</Text>
                            </TouchableOpacity>
                        </View>
                    }
                </View>
            }
        >
            <View style={[styles.container,{height: pageScrollBodyH - 8}]}>
                {selectVal === 1 && <ContentFeed synchronize={synchronize}/>}
                {selectVal === 2 && <FileFeed />}
            </View>

            <FcModal
                isOpen={setTap}
                onFcModalClose={() => SetSetTap(false)}
                titleText='设置标签'
                titleDesc='单个设置标签可以新增、删除批量设置只做新增'
                titleRight={
                    <TouchableOpacity style={styles.edit_box} onPress={() => router.push('/aiFeeding/editTap')}>
                        <Text style={styles.edit}>编辑</Text>
                    </TouchableOpacity>
                }
                bottom={
                    <View style={styles.tap_bottom}>
                        <TouchableOpacity style={{flexDirection: 'row', alignItems: 'center'}} onPress={() => setIsAdd(true)} >
                            <Text style={{fontFamily: 'FcIconFont', fontSize: 20,color: '#2856FF'}}>&#xe63a;</Text>
                            <Text style={{fontSize: 15, color: '#2856FF',marginLeft: 4}}>新增标签</Text>
                        </TouchableOpacity>
                        <FcButton
                            onClick={() => handleToSetTap()}
                            type='BjJB'
                            colors={seleteLabel.id?['#6989FF', '#C65EFD']:['rgba(105,137,255,0.4)','rgba(198,94,253,0.4)']}
                            style={{width: 88, height: 32, justifyContent: 'center'}}
                            itemStyle={{borderRadius: 8, fontSize: 15}}
                            textName='确认设置'/>
                    </View>
                }
            >
                {labelList?.map((item, index) => (
                    <>
                        {index > 1 &&
                            <View style={[styles.item_wrap, {marginHorizontal: 16}]} key={index}>
                                <View style={styles.item_left}>
                                    <TouchableOpacity
                                        style={[styles.select_icon, item.id === seleteLabel.id && styles.select_active]}
                                        onPress={() => setSelectLabel(item)}>
                                        {item.id === seleteLabel.id && <Text
                                            style={{fontFamily: 'FcIconFont', fontSize: 16, color: 'white'}}>&#xe64d;</Text>}
                                    </TouchableOpacity>
                                    <Text style={styles.search_text}>{item.name}</Text>
                                </View>
                            </View>
                        }
                    </>
                ))}

            </FcModal>

            <FcModal
                isOpen={isAdd}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsAdd(false)}
                style={styles.modal_default}
                titleText={'新增标签'}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsAdd(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => handleAddLabel(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <View style={{paddingBottom: 20}}>
                    <FcTextInput text={tapName} placeholder={'请输入标签名称'}
                                 onChangeText={setTapName}
                                 height={56}/>
                </View>
            </FcModal>
            <FcModal
                isOpen={isHint}
                transparent
                closeShow={false}
                animationType='fade'
                onFcModalClose={() => setIsHint(false)}
                style={styles.modal_default}
                titleText={hintTitle}
                titleBottomBorderWidth={0}
                footer={[
                    {
                        text: '取消',
                        onPress: () => setIsHint(false),
                        style: { color: 'rgba(0, 0, 0, 0.5)',fontSize: 17 },
                    },
                    {
                        text: '确认',
                        onPress: () => handleSure(),
                        style: { color: '#2856FF',fontSize: 17 },
                    },
                ]}
            >
                <Text style={{textAlign:'center',color: 'rgba(0,0,0,0.5)'}}>{hint}</Text>
            </FcModal>
        </PageScrollView>
    )
}

export default details

const styles = StyleSheet.create({
    container: {
        backgroundColor: 'white',
        // paddingHorizontal: 16,
        paddingBottom: 16
    },
    page_bottom: {
        backgroundColor: 'white',
        height: 48,
        paddingHorizontal: 16,
        position: "relative",
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between"
    },
    btn_item: {
        fontSize: 14,
        color: 'rgba(0,0,0,0.3)',
        flexDirection: "row",
        alignItems: "center",
    },
    btn_icon: {
        fontFamily: 'FcIconFont',
        fontSize: 14,
        color: 'rgba(0,0,0,0.3)'
    },
    btn_txt: {
        color: 'rgba(0,0,0,0.9)'
    },
    delete_text: {
        fontFamily: 'FcIconFont',
        fontSize: 14,
        color: 'rgba(250,81,81,0.3)'
    },
    delete_active: {
        color: 'rgba(250,81,81,1)'
    },

    tap_bottom: {
        backgroundColor: 'white',
        height: 48,
        flexDirection: "row",
        alignItems: "center",
        justifyContent: "space-between",
        paddingHorizontal: 16
    },
    item_wrap: {
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "space-between",
        minHeight: 56,
        display: 'flex',
        borderBottomWidth: 0.5,
        borderBottomColor: 'rgba(0,0,0,0.1)',
    },
    item_left: {
        flexDirection: 'row',
        alignItems: "center"
    },
    select_icon: {
        width: 20,
        height: 20,
        borderRadius: '50%',
        borderWidth: 1,
        borderColor: 'rgba(0,0,0,0.5)',
        marginRight: 12,
    },
    select_active: {
        borderColor: '#2856FF',
        backgroundColor: '#2856FF',
        flexDirection: 'row',
        alignItems: "center",
        justifyContent: "center"
    },
    search_text: {
        color: 'rgba(0, 0, 0, 0.9)'
    },
    edit_box: {
        paddingHorizontal: 12,
        height: 32,
        display: 'flex',
        justifyContent: 'center',
        alignItems: 'center',
        borderRadius: 8,
        backgroundColor: '#F1F2F4'
    },
    edit: {
        color: '#2856FF',
    },
    modal_default: {
        width: 280,
        borderBottomRightRadius: 12,
        borderBottomLeftRadius: 12,
    },
})